<template>
  <div>
    <el-row>
      <el-col :span="8">
        <el-input
          v-model="queryBody.title"
          :clearable="true"
          placeholder="请输入要搜索的文章标题"
          size="small"
          style="min-width: 520px"
          @clear="search"
          @keyup.native.enter="search"
        >
          <el-select
            slot="prepend"
            v-model="queryBody.categoryId"
            :clearable="true"
            placeholder="请选择文章分类"
            style="width: 160px"
            @change="search"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-input>
      </el-col>
    </el-row>
    <el-table :data="postList">
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="标题" prop="title" show-overflow-tooltip />
      <el-table-column label="分类" prop="category.name" width="150" />
      <el-table-column label="置顶" width="80">
        <template v-slot="scope">
          <el-switch v-model="scope.row.top" @change="togglePostTop(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="80">
        <template v-slot="scope">
          <el-switch v-model="scope.row.recommend" @change="togglePostRecommend(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="可见范围" width="100">
        <template v-slot="scope">
          <el-link :underline="false" icon="el-icon-edit" @click="handlePostSecurity(scope.row)">
            {{ getPostSecuritySetting(scope.row) }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template v-slot="scope">{{ scope.row.createTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column label="最近更新" width="170">
        <template v-slot="scope">{{ scope.row.updateTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="scope">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="goPostEditPage(scope.row.id)"
          >
            编辑
          </el-button>
          <el-popconfirm
            icon="el-icon-delete"
            iconColor="red"
            title="确定删除吗？"
            @onConfirm="deletePostById(scope.row.id)"
          >
            <el-button slot="reference" icon="el-icon-delete" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页-->
    <el-pagination
      v-if="total > 0"
      :current-page="queryBody.pageNum"
      :page-size="queryBody.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      background
      hide-on-single-page
      layout="total,sizes,prev,pager,next,jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--    文章安全设置dialog-->
    <security-setting-dialog
      :form="visForm"
      :is-show="dialogVisible"
      :radio="radio"
      @cancel="dialogVisible = false"
      @save="savePostSecuritySetting"
    />
  </div>
</template>

<script>
  import {
    deleteBlogById,
    getDataByQuery,
    updateRecommend,
    updateTop,
    updateVisibility,
  } from '@/api/blog'
  import SecuritySettingDialog from '@/views/blog/post/components/SecuritySettingDialog'

  export default {
    name: 'PostList',
    components: { SecuritySettingDialog },
    data() {
      return {
        queryBody: {
          title: '',
          categoryId: null,
          pageNum: 1,
          pageSize: 10,
        },
        postList: [],
        categoryList: [],
        total: 0,
        dialogVisible: false,
        postId: 0,
        radio: 1,
        visForm: {
          appreciation: false,
          recommend: false,
          commentEnabled: false,
          top: false,
          published: false,
          password: '',
        },
      }
    },
    computed: {},
    created() {
      this.fetchData()
    },
    methods: {
      // 获取文章列表数据
      fetchData() {
        getDataByQuery(this.queryBody).then((res) => {
          const { list, total } = res.data.blogs
          const { categoryList } = res.data.categories
          this.postList = list
          this.categoryList = categoryList
          this.total = total
        })
      },
      // 搜索文章
      search() {
        this.queryInfo.pageNum = 1
        this.queryInfo.pageSize = 10
        this.fetchData()
      },
      // 切换文章是否置顶
      togglePostTop(row) {
        updateTop(row.id, row.top).then((res) => {
          this.msgSuccess(res.msg)
        })
      },
      // 切换文章推荐状态
      togglePostRecommend(row) {
        updateRecommend(row.id, row.recommend).then((res) => {
          this.msgSuccess(res.msg)
        })
      },
      // 文章安全设置
      handlePostSecurity(row) {
        Object.keys(this.visForm).forEach((key) => {
          this.visForm[key] = row[key]
        })
        this.postId = row.id
        this.radio = this.visForm.published ? (this.visForm.password !== '' ? 3 : 1) : 2
        this.dialogVisible = true
      },
      // 计算文章可见设置
      getPostSecuritySetting(row) {
        return row.published ? (row.password !== '' ? '密码保护' : '公开') : '仅自己可见'
      },
      // 跳转编辑文章路由
      goPostEditPage(id) {
        this.$router.push(`/blog/post/edit/${id}`)
      },
      // 删除文章
      deletePostById(id) {
        this.$confirm(
          '此操作将永久删除该博客<strong style="color: red">及其所有评论</strong>，是否删除?<br>建议将博客置为<strong style="color: red">私密</strong>状态！',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          }
        )
          .then(() => {
            deleteBlogById(id).then((res) => {
              this.msgSuccess(res.msg)
              this.fetchData()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消删除',
            })
          })
      },
      // 监听 pageSize 改变事件
      handleSizeChange(newPageSize) {
        this.queryBody.pageSize = newPageSize
        this.fetchData()
      },
      // 监听当前页码改变事件
      handleCurrentChange(newCurrentNum) {
        this.queryBody.pageNum = newCurrentNum
        this.fetchData()
      },
      savePostSecuritySetting() {
        if (this.radio === 3 && !this.visForm.password) {
          return this.msgError('密码保护模式必须填写密码！')
        }
        if (this.radio === 2) {
          this.visForm.appreciation = false
          this.visForm.recommend = false
          this.visForm.commentEnabled = false
          this.visForm.top = false
          this.visForm.published = false
        } else {
          this.visForm.published = true
        }
        if (this.radio !== 3) {
          this.visForm.password = ''
        }
        updateVisibility(this.postId, this.visForm)
          .then((res) => {
            this.msgSuccess(res.msg)
            this.fetchData()
            this.dialogVisible = false
          })
          .catch((err) => {
            console.log(err)
          })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .el-button + span {
    margin-left: 10px;
  }
</style>
